package com.small.nacos.core.controller;

import com.alibaba.nacos.common.model.RestResult;
import com.alibaba.nacos.common.model.RestResultUtils;
import com.alibaba.nacos.common.utils.LoggerUtils;
import com.small.nacos.core.cluster.Member;
import com.small.nacos.core.cluster.NodeState;
import com.small.nacos.core.cluster.ServerMemberManager;
import com.small.nacos.core.utils.Commons;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author zhoujin
 * @Date 2022/11/11 16:19
 */
@RestController
@RequestMapping(Commons.NACOS_CORE_CONTEXT + "/cluster")
public class NacosClusterController {

    protected static final Logger LOGGER = LoggerFactory.getLogger(NacosClusterController.class);

    private final ServerMemberManager memberManager;

    public NacosClusterController(ServerMemberManager memberManager) {
        this.memberManager = memberManager;
    }

    @PostMapping(value = {"/report"})
    public RestResult<String> report(@RequestBody Member node) {
        if (!node.check()) {
            return RestResultUtils.failedWithMsg(400, "Node information is illegal");
        }
        LoggerUtils.printIfDebugEnabled(LOGGER, "node state report, receive info : {}", node);
        node.setState(NodeState.UP);
        node.setFailAccessCnt(0);

        boolean result = memberManager.update(node);

        return RestResultUtils.success(Boolean.toString(result));
    }
}
